package addition.chat;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天客户机
 */
public class ChatClient {

    /**
     * Scanner
     */
    private final static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        while (true) {
            Socket client = new Socket("localhost", 8080);
            InputStream is = client.getInputStream();
            OutputStream os = client.getOutputStream();

            // Input message
            System.out.print("> ");
            String message = scanner.nextLine();
            if ("bye".equals(message)) {
                System.out.println("> bye!");
                break;
            }

            // Send message
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,
                    StandardCharsets.UTF_8));
            bw.write(message + "\n");
            bw.flush();

            String replyMessage = ChatServer.getMessage(is, "UTF-8");  // Server reply
            System.out.printf("> Robot: %s%n", replyMessage);
            is.close();
            os.close();
            client.close();
        }
    }

}
